package Com.Ring.TradingMobile;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import Com.Ring.TradingMobile.Lib.Common;
import Com.Ring.TradingMobile.Lib.Common.MARKET;
import Com.Ring.TradingMobile.Lib.CompanyListAdapter;
import Com.Ring.TradingMobile.Object.CompanyInfo;
import Com.Ring.TradingMobile.Object.Config;
import Com.Ring.TradingMobile.Object.DanhMuc;
import Com.Ring.TradingMobile.Object.ItemDanhMuc;
import Com.Ring.TradingMobile.Object.MarketInfo;
import Com.Ring.TradingMobile.Object.StockInfo;
import Com.Ring.TradingMobile.SQLite.DBManager;
import Com.Ring.TradingMobile.Service.WebService;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class ThiTruongActivity extends Activity {

	private static final int DIALOG_LOADING = 0;

	public boolean IsRealTime = true;
	public long Interval = 10000;

	public MARKET marketEnum;
	private DanhMuc danhMuc;

	private int[] StrHeaderId = new int[]{R.string.strMaCK, R.string.strRef,
			R.string.strCeiling, R.string.strFloor, R.string.strLast,
			R.string.strChange, R.string.strVol, R.string.strBestBuyPrice,
			R.string.strBestBuyVol, R.string.strBestSellPrice,
			R.string.strBestSellVol, R.string.strTotalVol};

	private Spinner DropListMarket;
	private CheckBox CheckRealTime;
	private AutoCompleteTextView AutoCompleteStock;
	private LinearLayout linearHeader;
	private LinearLayout linearContent;
	private TextView lblIndex;
	private TextView lblKLAndGT;
	private TextView lblStatusCurrent;
	private TextView lblDanhMuc;
	private Button btnBack;
	private Button btnHome;
	private Button btnThem;
	private Button btnXoa;

	public boolean IsUpdateCompany;
	public boolean IsUpdateStockInfoRunning;
	public boolean IsRunningUpdate;
	public boolean IsSave;
	public boolean IsReady = false;
	private int PositionDropListMarket = 0;
	private DBManager dbDataComplete;
	private DBManager dbDataAutoUpdateStock;
	private DBManager dbDataMarket;
	private String TAG = "ThiTruong";

	public List<String> CodeArray = new ArrayList<String>();

	private Class<? extends Activity> ActivityCallBack;

	private CompanyInfoAsyncTask companyInfoAsyncTask;
	private MarketInfoAsyncTask marketInfoAsyncTask;
	private StockInfoAsyncTask stockInfoAsyncTask;
	private MarketInfoEventAsyncTask marketInfoEventAsyncTask;
	private StockInfoEventAsyncTask stockInfoEventAsyncTask;

	private boolean IsHandlerEventPressMarket = false;
	private boolean IsHandlerEventPressStock = false;

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case DIALOG_LOADING : {
				ProgressDialog dialog = new ProgressDialog(this);
				dialog.setMessage("Please wait while loading...");
				dialog.setIndeterminate(true);
				dialog.setCancelable(true);
				return dialog;
			}
		}
		return null;
	}

	@Override
	protected void onPause() {
		Log.d(TAG, "On Pause");
		super.onPause();
	}

	@Override
	protected void onRestart() {
		Log.d(TAG, "On Restart");
		super.onRestart();
	}

	@Override
	protected void onResume() {
		Log.d(TAG, "On Resume");
		super.onResume();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.thitruong_main);
		// get data from another activity
		danhMuc = new DanhMuc();
		Bundle bund = getIntent().getExtras();
		String[] arrayStr = bund.getStringArray(Common.KeyIntentThiTruong);
		marketEnum = Common.ConvertToEnumMarket(Integer.parseInt(arrayStr[0]));
		// DBManager dbData = new DBManager(this);
		Cursor cur;
		DBManager dbData = new DBManager(this);
		cur = dbData.Select("select * from " + DanhMuc.TABLE_NAME + " where "
				+ DanhMuc.NAME_DANH_MUC + " = '" + arrayStr[1] + "' ");
		if (cur.getCount() > 0) {
			while (cur.moveToNext()) {
				danhMuc.Name_Danh_Muc = cur.getString(cur
						.getColumnIndex(DanhMuc.NAME_DANH_MUC));
				danhMuc.Id_Danh_Muc = cur.getInt(cur
						.getColumnIndex(DanhMuc.ID_DANH_MUC));
			}
		}
		cur.close();
		dbData.close();
		CodeArray = GetCodesFromList(danhMuc.Id_Danh_Muc);
		FindViewById();
		InitControlListener();
		ActivityCallBack = arrayStr[2].equals("0")
				? TradingMobileActivity.class
				: DanhMucActivity.class;
		BindingData();
		Log.d(TAG, "On Create");

	}

	private List<String> GetCodesFromList(int idDanhMuc) {
		DBManager dbData = new DBManager(this);
		List<String> listCode = new ArrayList<String>();
		Cursor cur = null;
		try {
			cur = dbData.Select("select " + ItemDanhMuc.CODE + " from "
					+ ItemDanhMuc.TABLE_NAME + " where "
					+ ItemDanhMuc.ID_DANH_MUC + " = " + idDanhMuc + " ");
			if (cur.getCount() > 0) {
				while (cur.moveToNext()) {
					listCode.add(cur.getString(cur
							.getColumnIndex(ItemDanhMuc.CODE)));
				}
			}
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		} finally {
			if (cur != null) {
				cur.close();
			}
			if (dbData != null) {
				dbData.close();
			}
		}
		return listCode;
	}

	OnItemSelectedListener ListenerDropListMarket = new OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> parent, View v, int position,
				long id) {
			if (position != PositionDropListMarket) {
				PositionDropListMarket = position;
				marketEnum = Common.ConvertToEnumMarket(position + 1);
				IsHandlerEventPressMarket = true;
				LoadMarketInfoEvent();
			}
		}

		public void onNothingSelected(AdapterView<?> arg0) {

		}
	};

	private void BindingData() {
		// Auto Check RealTime
		DBManager dbData = new DBManager(this);
		Cursor cur;
		cur = dbData.Select("select * from " + Config.TABLE_NAME);
		if (cur.getCount() > 0) {
			while (cur.moveToNext()) {
				IsRealTime = cur.getInt(cur.getColumnIndex(Config.IS_REALTIME)) == 1
						? true
						: false;
				IsSave = cur.getInt(cur.getColumnIndex(Config.AUTO_SAVE)) == 1
						? true
						: false;
				Interval = cur.getLong(cur.getColumnIndex(Config.INTERVAL));

			}
		}
		cur.close();
		dbData.close();
		CheckRealTime.setChecked(IsRealTime);
		// Binding data for Drop Down list Market
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.Market, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		DropListMarket.setAdapter(adapter);
		DropListMarket.setSelection(0);
		lblDanhMuc.setText(danhMuc.Name_Danh_Muc);
	}

	private void FindViewById() {
		DropListMarket = (Spinner) findViewById(R.id.dropDownListMarket);
		CheckRealTime = (CheckBox) findViewById(R.id.chkRealTime);
		AutoCompleteStock = (AutoCompleteTextView) findViewById(R.id.autoCompleteMarket);
		AutoCompleteStock.setThreshold(1);
		linearHeader = (LinearLayout) findViewById(R.id.linearHeader);
		linearContent = (LinearLayout) findViewById(R.id.linearContent);
		lblIndex = (TextView) findViewById(R.id.lblIndex);
		lblKLAndGT = (TextView) findViewById(R.id.lblKLAndGT);
		lblStatusCurrent = (TextView) findViewById(R.id.lblStatusCurrent);
		lblDanhMuc = (TextView) findViewById(R.id.lblDanhMuc);
		btnBack = (Button) findViewById(R.id.btnBack);
		btnHome = (Button) findViewById(R.id.btnHome);
		btnThem = (Button) findViewById(R.id.btnThem);
		btnXoa = (Button) findViewById(R.id.btnXoa);

		/*
		 * Initialization Create Header
		 */
		TableLayout tableHeader = new TableLayout(this);
		TableRow[] rowsHeader = new TableRow[StrHeaderId.length];
		TextView[] txtHeader = new TextView[StrHeaderId.length];
		for (int i = 0; i < txtHeader.length; i++) {
			rowsHeader[i] = new TableRow(this);
			txtHeader[i] = new TextView(this);
			txtHeader[i].setText(StrHeaderId[i]);
			txtHeader[i].setHeight(26);
			txtHeader[i].setTextSize(12);
			txtHeader[i]
					.setBackgroundResource(R.drawable.border_color_textview);
			txtHeader[i].setTextColor(getResources().getColor(R.color.whiles));
			rowsHeader[i].addView(txtHeader[i]);
			tableHeader.addView(rowsHeader[i]);
		}
		linearHeader.addView(tableHeader);

	}

	private void InitControlListener() {
		btnThem.setOnClickListener(themListener);
		btnXoa.setOnClickListener(xoaListener);
		CheckRealTime.setOnCheckedChangeListener(listenerRealtime);
		DropListMarket.setOnItemSelectedListener(ListenerDropListMarket);
		btnBack.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		btnHome.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), ActivityCallBack);
				startActivity(intent);
				finish();
			}
		});
		

	}

	/*
	 * Event Listen
	 */

	OnCheckedChangeListener listenerRealtime = new OnCheckedChangeListener() {
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			IsRealTime = isChecked;
			IsUpdateStockInfoRunning = IsRealTime;
			IsHandlerEventPressMarket = true;
			IsHandlerEventPressStock = true;
			LoadStockEvent("", "");
			LoadMarketInfoEvent();

		}
	};
	OnClickListener themListener = new OnClickListener() {
		public void onClick(View v) {
			try {
				String code = AutoCompleteStock.getText().toString().trim();
				if (!code.equals("") && code.length() >= 3) {
					AutoCompleteStock.setText("");
					if (!CodeArray.contains(code)) {
						IsHandlerEventPressStock = true;
						LoadStockEvent(code, "1");
					}
				}
			} catch (Exception e) {
				Log.d(TAG, e.getMessage());
			}
		}
	};

	OnClickListener xoaListener = new OnClickListener() {
		public void onClick(View v) {
			String code = AutoCompleteStock.getText().toString().trim();
			if (!code.equals("") && code.length() >= 3) {
				AutoCompleteStock.setText("");
				if (CodeArray.contains(code)) {
					CodeArray.remove(code);
					if (CodeArray.isEmpty())
						linearContent.removeAllViewsInLayout();
					LoadStockEvent(code, "0");
				}
			}
		}
	};

	@Override
	protected void onStart() {
		super.onStart();
		Log.d(TAG, "On Start");
		showDialog(DIALOG_LOADING);
		IsUpdateStockInfoRunning = false;
		dbDataAutoUpdateStock = new DBManager(this);
		dbDataComplete = new DBManager(this);
		dbDataMarket = new DBManager(this);
		LoadCompanyInfo();
		LoadMarketInfo();
		LoadStockInfo();
	}

	@Override
	protected void onStop() {
		CancelLoadCompanyInfo();
		CancelLoadMarketInfo();
		CancelLoadStockInfo();
		CancelLoadMarketInfoEvent();
		CancelLoadStockInfoEvent();
		dbDataAutoUpdateStock.close();
		dbDataComplete.close();
		dbDataMarket.close();
		Log.d(TAG, "On Stop");
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		Log.d(TAG, "On Destroy");
		if (companyInfoAsyncTask != null) {
			companyInfoAsyncTask.cancel(true);
			companyInfoAsyncTask = null;
		}
		super.onDestroy();
	}

	private void LoadCompanyInfo() {
		final Calendar c = Calendar.getInstance();
		Log.d(TAG, c.getTime().toLocaleString());
		CancelLoadCompanyInfo();
		companyInfoAsyncTask = new CompanyInfoAsyncTask();
		companyInfoAsyncTask.execute(0);
	}

	private void CancelLoadCompanyInfo() {
		if (companyInfoAsyncTask != null) {
			companyInfoAsyncTask.cancel(true);
			companyInfoAsyncTask = null;
		}
	}

	private void LoadMarketInfo() {
		CancelLoadMarketInfo();
		marketInfoAsyncTask = new MarketInfoAsyncTask();
		marketInfoAsyncTask.execute();
	}

	private void LoadMarketInfoEvent() {
		CancelLoadMarketInfoEvent();
		marketInfoEventAsyncTask = new MarketInfoEventAsyncTask();
		marketInfoEventAsyncTask.execute();
	}

	private void CancelLoadMarketInfo() {
		if (marketInfoAsyncTask != null
				&& marketInfoAsyncTask.getStatus() == Status.RUNNING) {
			marketInfoAsyncTask.cancel(true);
			marketInfoAsyncTask = null;
		}
	}

	private void CancelLoadMarketInfoEvent() {
		if (marketInfoEventAsyncTask != null
				&& marketInfoEventAsyncTask.getStatus() == Status.RUNNING) {
			marketInfoEventAsyncTask.cancel(true);
			marketInfoEventAsyncTask = null;
		}
	}

	private void CancelLoadStockInfoEvent() {
		if (stockInfoEventAsyncTask != null
				&& stockInfoEventAsyncTask.getStatus() == Status.RUNNING) {
			stockInfoEventAsyncTask.cancel(true);
			stockInfoEventAsyncTask = null;
		}
	}

	private void LoadStockInfo() {
		CancelLoadStockInfo();
		stockInfoAsyncTask = new StockInfoAsyncTask();
		stockInfoAsyncTask.execute();
	}

	private void LoadStockEvent(String code, String editOrAdd) {
		CancelLoadStockInfoEvent();
		stockInfoEventAsyncTask = new StockInfoEventAsyncTask();
		if (code != "")
			stockInfoEventAsyncTask.execute(code, editOrAdd);
		else
			stockInfoEventAsyncTask.execute();
	}

	private void CancelLoadStockInfo() {
		if (stockInfoAsyncTask != null) {
			stockInfoAsyncTask.cancel(true);
			stockInfoAsyncTask = null;
		}
	}

	private class StockInfoAsyncTask
			extends
				AsyncTask<Void, List<StockInfo>, List<StockInfo>> {

		@SuppressWarnings("unchecked")
		@Override
		protected List<StockInfo> doInBackground(Void... params) {
			List<StockInfo> listStockInfo = new ArrayList<StockInfo>();
			// DBManager dbData = new DBManager(ThiTruongActivity.this);
			while (true) {
				if (isCancelled())
					break;
				try {
					Log.d(TAG, "Update Stock: Sleep" + (Interval * 1000));
					if (IsUpdateStockInfoRunning = true && !IsHandlerEventPressStock) {
						List<StockInfo> listItem = GetListStockInfo(CodeArray);
						if (listItem != null && listItem.size() > 0) {
							listStockInfo.clear();
							listStockInfo.addAll(listItem);
							publishProgress(listStockInfo);
							dbDataAutoUpdateStock
									.InsertStockInfoList(listStockInfo);
						}
					}
					Thread.sleep(Interval * 1000);
				} catch (Exception e) {
					Log.d(TAG, e.getMessage());
				}
			}
			// dbData.close();
			return listStockInfo;
		}

		@Override
		protected void onCancelled() {
			
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(List<StockInfo> listStockInfo) {

		}

		@Override
		protected void onPreExecute() {
			
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(List<StockInfo>... listStockInfo) {
			UpdateStockInfoUI(listStockInfo);
		}

	}

	private class StockInfoEventAsyncTask
			extends
				AsyncTask<String, List<StockInfo>, List<StockInfo>> {

		@SuppressWarnings("unchecked")
		@Override
		protected List<StockInfo> doInBackground(String... params) {
			if (params != null && params.length > 0) {
				if (params[1].equals("0")) {
					dbDataAutoUpdateStock.DeleteItemDanhMuc(
							danhMuc.Id_Danh_Muc, params[0]);
				} else if (params[1].equals("1")) {
					Boolean isAdd = true;
					if (!IsRealTime) {
						Cursor cursor;
						cursor = dbDataAutoUpdateStock.Select("select * from "
								+ ItemDanhMuc.TABLE_NAME + " where "
								+ ItemDanhMuc.ID_DANH_MUC + " = "
								+ danhMuc.Id_Danh_Muc + " and "
								+ ItemDanhMuc.CODE + " = '" + params[0] + "'");
						if (cursor != null && cursor.getCount() > 0)
							isAdd = true;
						else {
							isAdd = false;
						}
						cursor.close();
					}
					if (isAdd) {
						dbDataAutoUpdateStock.InsertItemDanhMuc(
								danhMuc.Id_Danh_Muc, params[0]);
						CodeArray.add(0, params[0]);
					}
				}
			}

			//
			List<StockInfo> listStockInfo = new ArrayList<StockInfo>();
			try {
				Log.d(TAG, "Update Stock Event");
				List<StockInfo> listItem = GetListStockInfo(CodeArray);
				if (listItem != null && listItem.size() > 0) {
					listStockInfo.clear();
					listStockInfo.addAll(listItem);
					publishProgress(listStockInfo);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return listStockInfo;
		}

		@Override
		protected void onCancelled() {
			
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(List<StockInfo> listStockInfo) {

		}

		@Override
		protected void onPreExecute() {
			
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(List<StockInfo>... listStockInfo) {
			UpdateStockInfoUI(listStockInfo);
			IsHandlerEventPressStock = false;

		}

	}

	private List<StockInfo> GetListStockInfo(List<String> codeArraysList) {
		List<StockInfo> listStockInfo = null;
		// DBManager dbData = new DBManager(ThiTruongActivity.this);
		if (IsRealTime) {
			WebService service = new WebService();
			if (codeArraysList.size() > 0) {
				String codes = codeArraysList.get(0);
				for (int i = 1; i < codeArraysList.size(); i++) {
					codes = codes + "," + codeArraysList.get(i);
				}
				listStockInfo = service.GetListStockInfo(codes, 1);
			}
		} else {
			if (codeArraysList.size() > 0) {
				StringBuilder whereArg = new StringBuilder();
				whereArg.append(StockInfo.SYMBOL);
				whereArg.append("='");
				whereArg.append(codeArraysList.get(0));
				whereArg.append("'");
				for (int i = 1; i < codeArraysList.size(); i++) {
					whereArg.append(" or ");
					whereArg.append(StockInfo.SYMBOL);
					whereArg.append("='");
					whereArg.append(codeArraysList.get(i));
					whereArg.append("'");
				}
				// select max Trade_Date
				Cursor cur;
				cur = dbDataAutoUpdateStock.Select("select "
						+ StockInfo.TRADE_DATE + " from "
						+ StockInfo.TABLE_NAME
						+ " where _id = (select max(_id) from "
						+ StockInfo.TABLE_NAME + ") limit 1");
				if (cur.moveToNext()) {
					cur.getString(cur.getColumnIndex(StockInfo.TRADE_DATE));
					Log.d(TAG, cur.getString(cur
							.getColumnIndex(StockInfo.TRADE_DATE)));
					whereArg.append(" and ");
					whereArg.append(StockInfo.TRADE_DATE);
					whereArg.append("='");
					whereArg.append(cur.getString(0));
					whereArg.append("'");
				}

				String sql = String.format("select * from %s where %s ",
						StockInfo.TABLE_NAME, whereArg);
				Log.d(TAG, sql);
				Cursor listStockCursor;
				listStockCursor = dbDataAutoUpdateStock.Select(sql);

				if (listStockCursor.getCount() > 0) {
					listStockInfo = new ArrayList<StockInfo>();
					while (listStockCursor.moveToNext()) {
						StockInfo stock = new StockInfo();
						stock.Symbol = listStockCursor
								.getString(listStockCursor
										.getColumnIndex(StockInfo.SYMBOL));
						stock.RefPrice = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.REF_PRICE));
						stock.CeilPrice = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.CEIL_PRICE));
						stock.FloorPrice = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.FLOOR_PRICE));
						stock.PriceMatch = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.PRICE_MATCH));
						stock.Changed = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.CHANGED));
						stock.PerChanged = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.PER_CHANGED));
						stock.VolumeMatch = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.VOLUME_MATCH));
						stock.TotalMatch = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.TOTAL_MATCH));

						stock.BestPriceBuy = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.BEST_PRICE_BUY));
						stock.BestVolbuy = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.BEST_VOL_BUY));
						stock.BestPriceSell = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.BEST_PRICE_SELL));
						stock.BestVolSell = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.BEST_VOL_SELL));
						stock.TradeDate = listStockCursor
								.getString(listStockCursor
										.getColumnIndex(StockInfo.TRADE_DATE));
						listStockInfo.add(stock);
					}
					cur.close();
					listStockCursor.close();
				}

			}
		}
		// dbData.close();
		return listStockInfo;
	}

	private class MarketInfoAsyncTask
			extends
				AsyncTask<Void, MarketInfo, MarketInfo> {

		@Override
		protected MarketInfo doInBackground(Void... params) {
			MarketInfo marketInfo = null;
			while (true) {
				if (isCancelled())
					break;
				try {
					if (!IsHandlerEventPressMarket) {
						marketInfo = GetMarketInfo(PositionDropListMarket + 1);
						publishProgress(marketInfo);
					}
					Log.d(TAG, "UpdateMarket: Sleep " + (Interval * 1000));
					Thread.sleep(Interval * 1000);
				} catch (InterruptedException e) {
					Log.d(TAG, e.getMessage());
				}
			}

			return marketInfo;
		}

		@Override
		protected void onCancelled() {
			
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(MarketInfo marketInfo) {

		}

		@Override
		protected void onPreExecute() {
			
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(MarketInfo... marketInfo) {
			if (IsHandlerEventPressMarket)
				return;
			if (marketInfo != null)
				UpdateMarketUI(marketInfo);
		}

	}

	private class MarketInfoEventAsyncTask
			extends
				AsyncTask<Void, MarketInfo, MarketInfo> {

		@Override
		protected MarketInfo doInBackground(Void... params) {
			MarketInfo marketInfo = null;
			try {
				marketInfo = GetMarketInfo(PositionDropListMarket + 1);
				publishProgress(marketInfo);
				Log.d(TAG, "UpdateMarketEvent: Sleep " + (Interval * 1000));
			} catch (Exception e) {
				Log.d(TAG, e.getMessage());
			}
			return marketInfo;
		}

		@Override
		protected void onCancelled() {
			
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(MarketInfo marketInfo) {

		}

		@Override
		protected void onPreExecute() {
			
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(MarketInfo... marketInfo) {
			UpdateMarketUI(marketInfo);
			IsHandlerEventPressMarket = false;
		}

	}

	private int SetColorMarketInfo(float indexChange) {
		if (indexChange > 0)
			return R.color.up;
		else if (indexChange < 0)
			return R.color.down;
		return R.color.nochange;
	}

	private MarketInfo GetMarketInfo(int MarketId) {
		MarketInfo marketInfo = null;
		// DBManager dbData = new DBManager(ThiTruongActivity.this);
		if (IsRealTime) {
			WebService service = new WebService();
			marketInfo = service.GetMarketInfoAndStatus(MarketId);
			dbDataMarket.InsertMarketInfo(marketInfo);

		} else {
			String sql = "select * from " + MarketInfo.TABLE_NAME
					+ " where _id = (select max(_id) from "
					+ MarketInfo.TABLE_NAME + " where " + MarketInfo.MARKET_ID
					+ " = " + MarketId + ")";
			Cursor cur;
			cur = dbDataMarket.Select(sql);
			if (cur.getCount() > 0) {
				marketInfo = new MarketInfo();
				while (cur.moveToNext()) {
					marketInfo.marketid = MarketId;
					// marketInfo.CountFloor = cur.getFloat(cur
					// .getColumnIndex(MarketInfo.COUNT_FLOOR));
					marketInfo.IndexChanged = cur.getFloat(cur
							.getColumnIndex(MarketInfo.INDEX_CHANGED));
					marketInfo.SetIndex = cur.getFloat(cur
							.getColumnIndex(MarketInfo.SET_INDEX));
					marketInfo.Status = cur.getString(cur
							.getColumnIndex(MarketInfo.STATUS));
					marketInfo.Time = cur.getInt(cur
							.getColumnIndex(MarketInfo.TIME));
					marketInfo.TotalShares = cur.getFloat(cur
							.getColumnIndex(MarketInfo.TOTAL_SHARES));
					marketInfo.TotalValues = cur.getFloat(cur
							.getColumnIndex(MarketInfo.TOTAL_VALUES));
					marketInfo.TradeDate = cur.getString(cur
							.getColumnIndex(MarketInfo.TRADE_DATE));
				}
			}
			cur.close();
		}
		// dbData.close();
		return marketInfo;
	}

	private void UpdateMarketUI(MarketInfo... marketInfo) {
		if (marketInfo[0] == null) {
			lblIndex.setText("");
			lblKLAndGT.setText("");
			lblKLAndGT.setText("");
			lblStatusCurrent.setText("");
			return;
		}
		String setIndex = Common.FormatShortNumber(marketInfo[0].SetIndex);
		String indexChange = Common
				.FormatShortNumber(marketInfo[0].IndexChanged);
		Log.d(TAG, "TotalValues: " + marketInfo[0].TotalValues);
		Log.d(TAG, "TotalShare: " + marketInfo[0].TotalShares);
		String totalValue = Common.FormatShortNumber(marketEnum == MARKET.HOSE
				? marketInfo[0].TotalValues * 100000
				: marketInfo[0].TotalValues);
		String volume = Common.FormatShortNumber(marketInfo[0].TotalShares);
		float ref = marketInfo[0].SetIndex - marketInfo[0].IndexChanged;
		String perChange = ref > 0
				? Common.FormatShortNumber(marketInfo[0].IndexChanged / ref
						* 100)
				: "0";
		lblIndex.setText(setIndex + " " + indexChange + "(" + perChange + ")");
		lblIndex.setTextColor(getResources().getColor(
				SetColorMarketInfo(marketInfo[0].IndexChanged)));
		lblKLAndGT.setText(volume + " | " + totalValue);
		lblKLAndGT.setTextColor(getResources().getColor(R.color.whiles));
		lblStatusCurrent.setText(getResources().getString(
				Common.GetMarketStatus(marketEnum, marketInfo[0].Status)));
	}

	private void UpdateStockInfoUI(List<StockInfo>... listStockInfo) {
		if (listStockInfo[0] != null && listStockInfo[0].size() > 0) {
			linearContent.removeAllViewsInLayout();
			String text = null;
			int color = 0;
			for (StockInfo stockInfo : listStockInfo[0]) {
				TableLayout tableContent = new TableLayout(
						ThiTruongActivity.this);
				TableRow[] rowContents = new TableRow[StrHeaderId.length];

				TextView[] txtContent = new TextView[StrHeaderId.length];
				for (int i = 0; i < txtContent.length; i++) {
					rowContents[i] = new TableRow(ThiTruongActivity.this);

					txtContent[i] = new TextView(ThiTruongActivity.this);
					// set text
					switch (i) {
						case 0 :
							text = stockInfo.Symbol;
							color = Common.SetColorStockInfo(
									stockInfo.PriceMatch, stockInfo.CeilPrice,
									stockInfo.FloorPrice, stockInfo.RefPrice);
							break;
						case 1 :
							text = Common.FormatNumber(stockInfo.RefPrice);
							color = R.color.nochange;
							break;
						case 2 :
							text = Common.FormatNumber(stockInfo.CeilPrice);
							color = R.color.ceilling;
							break;
						case 3 :
							text = Common.FormatNumber(stockInfo.FloorPrice);
							color = R.color.floor;
							break;
						case 4 :
							text = Common.FormatNumber(stockInfo.PriceMatch);
							color = Common.SetColorStockInfo(
									stockInfo.PriceMatch, stockInfo.CeilPrice,
									stockInfo.FloorPrice, stockInfo.RefPrice);
							break;
						case 5 :
							text = Common.FormatNumber(stockInfo.Changed);
							color = Common.SetColorStockInfo(
									stockInfo.PriceMatch, stockInfo.CeilPrice,
									stockInfo.FloorPrice, stockInfo.RefPrice);
							break;
						case 6 :
							text = Common.FormatNumber(stockInfo.VolumeMatch);
							color = Common.SetColorStockInfo(
									stockInfo.PriceMatch, stockInfo.CeilPrice,
									stockInfo.FloorPrice, stockInfo.RefPrice);
							break;
						case 7 :
							text = Common.FormatNumber(stockInfo.BestPriceBuy);
							color = Common.SetColorStockInfo(
									stockInfo.BestPriceBuy,
									stockInfo.CeilPrice, stockInfo.FloorPrice,
									stockInfo.RefPrice);
							break;
						case 8 :
							text = Common.FormatNumber(stockInfo.BestVolbuy);
							color = Common.SetColorStockInfo(
									stockInfo.BestPriceBuy,
									stockInfo.CeilPrice, stockInfo.FloorPrice,
									stockInfo.RefPrice);
							break;
						case 9 :
							text = Common.FormatNumber(stockInfo.BestPriceSell);
							color = Common.SetColorStockInfo(
									stockInfo.BestPriceSell,
									stockInfo.CeilPrice, stockInfo.FloorPrice,
									stockInfo.RefPrice);
							break;
						case 10 :
							text = Common.FormatNumber(stockInfo.BestVolSell);
							color = Common.SetColorStockInfo(
									stockInfo.BestPriceSell,
									stockInfo.CeilPrice, stockInfo.FloorPrice,
									stockInfo.RefPrice);
							break;
						case 11 :
							text = Common.FormatNumber(stockInfo.TotalMatch);
							color = Common.SetColorStockInfo(
									stockInfo.PriceMatch, stockInfo.CeilPrice,
									stockInfo.FloorPrice, stockInfo.RefPrice);
							break;
					}

					txtContent[i].setText(text);
					txtContent[i].setTextColor(getResources().getColor(color));
					txtContent[i].setHeight(26);
					txtContent[i].setTextSize(12);
					txtContent[i].setGravity(Gravity.CENTER_VERTICAL);
					txtContent[i].setPadding(0, 0, 2, 0);
					LayoutParams layout = new LayoutParams(
							LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT);
					// layout.width = 50;
					txtContent[i].setLayoutParams(layout);

					txtContent[i]
							.setBackgroundResource(R.drawable.border_color_textview);
					rowContents[i].addView(txtContent[i], layout);
					tableContent.addView(rowContents[i]);
				}
				// add row virtual
				TableRow rowVirtual = new TableRow(ThiTruongActivity.this);
				tableContent.addView(rowVirtual);
				//
				linearContent.addView(tableContent);
			}
		}
	}

	private class CompanyInfoAsyncTask
			extends
				AsyncTask<Integer, List<CompanyInfo>, List<CompanyInfo>> {
		@Override
		protected List<CompanyInfo> doInBackground(Integer... params) {
			WebService service = new WebService();
			List<CompanyInfo> companyList = null;
			if (IsRealTime) {
				companyList = service.GetCompanyList(params[0]);
				if (companyList != null && companyList.size() > 0) {
					publishProgress(companyList);
					dbDataComplete.InsertCompanyList(companyList);
				}
			}
			return companyList;
		}

		@Override
		protected void onCancelled() {
			
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(List<CompanyInfo> result) {
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(List<CompanyInfo>... result) {
			removeDialog(DIALOG_LOADING);
			IsUpdateStockInfoRunning = true;
			CompanyListAdapter adapter = new CompanyListAdapter(
					ThiTruongActivity.this, TAG, ThiTruongActivity.this,
					R.layout.two_line_list_item, null);
			AutoCompleteStock.setAdapter(adapter);
		}

	}
}
